import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface Task {
  id: string
  type: string
  inputFile: string
  outputFile: string
  status: 'pending' | 'processing' | 'completed' | 'failed'
  progress: number
  createdAt: number
  completedAt?: number
  error?: string
}

export const useTaskStore = defineStore(
  'task',
  () => {
    const tasks = ref<Task[]>([])
    const currentTask = ref<Task | null>(null)

    const addTask = (task: Omit<Task, 'id' | 'status' | 'progress' | 'createdAt'>) => {
      const newTask: Task = {
        ...task,
        id: Date.now().toString(),
        status: 'pending',
        progress: 0,
        createdAt: Date.now()
      }
      tasks.value.unshift(newTask)
      return newTask
    }

    const updateTask = (id: string, updates: Partial<Task>) => {
      const task = tasks.value.find((t) => t.id === id)
      if (task) {
        Object.assign(task, updates)
      }
    }

    const removeTask = (id: string) => {
      const index = tasks.value.findIndex((t) => t.id === id)
      if (index !== -1) {
        tasks.value.splice(index, 1)
      }
    }

    const clearCompleted = () => {
      tasks.value = tasks.value.filter((t) => t.status !== 'completed')
    }

    return {
      tasks,
      currentTask,
      addTask,
      updateTask,
      removeTask,
      clearCompleted
    }
  },
  {
    persist: true
  }
)
